package com.usaas.search.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.collection.ListUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.usaas.common.core.domain.AjaxResult;
import com.usaas.search.dto.PlatUserCollectDto;
import com.usaas.search.enums.PlatUserCollectEnums;
import com.usaas.search.mapper.PlatUserCollectMapper;
import com.usaas.search.pojo.PlatGameInfoPojo;
import com.usaas.search.pojo.PlatUserCollectPojo;
import com.usaas.search.pojo.PlatWelfareMessagePojo;
import com.usaas.search.service.IPlatGameInfoService;
import com.usaas.search.service.IPlatUserCollectService;
import com.usaas.search.service.IPlatWelfareMessageService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 用户收藏Service业务层处理
 *
 * @author Helios
 * @date 2024-08-14
 */
@Slf4j
@Service
public class PlatUserCollectServiceImpl extends ServiceImpl<PlatUserCollectMapper, PlatUserCollectPojo> implements IPlatUserCollectService {

    @Resource
    private PlatUserCollectMapper platUserCollectMapper;


    @Autowired
    private IPlatGameInfoService gameInfoService;
    @Autowired
    private IPlatWelfareMessageService platWelfareMessageService;

    /**
     * 查询用户收藏
     *
     * @param id 用户收藏主键
     * @return 用户收藏
     */
    @Override
    public PlatUserCollectDto queryById(Long id) {
        PlatUserCollectPojo pojo = this.getById(id);
        if (pojo != null) {
            PlatUserCollectDto dto = BeanUtil.copyProperties(pojo, PlatUserCollectDto.class);
            List<PlatUserCollectDto> dtos = ListUtil.of(dto);
            convertList(dtos);
            return dtos.get(0);
        }
        return null;
    }

    /**
     * 查询用户收藏列表
     *
     * @param platUserCollectDto 用户收藏
     * @return 用户收藏
     */
    @Override
    public List<PlatUserCollectDto> queryList(PlatUserCollectDto platUserCollectDto) {
        LambdaQueryWrapper<PlatUserCollectPojo> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper = this.buildWrapper(queryWrapper, platUserCollectDto);
        if (queryWrapper == null) {
            return null;
        }
        List<PlatUserCollectPojo> list = this.list(queryWrapper);
        if (CollectionUtil.isEmpty(list)) {
            return null;
        }

        List<PlatUserCollectDto> dtoList = BeanUtil.copyToList(list, PlatUserCollectDto.class);
        convertList(dtoList);
        return dtoList;
    }

    private void convertList(List<PlatUserCollectDto> dtoList) {
        if (CollectionUtil.isEmpty(dtoList)) {
            return;
        }
        List<Long> welflareIdList = new ArrayList<>();
        List<Long> gameIdList = new ArrayList<>();

        Map<Long, PlatWelfareMessagePojo> platWelfareMessageMap = new HashMap<>();
        Map<Long, PlatGameInfoPojo> gameMap = new HashMap<>();
        for (PlatUserCollectDto platUserCollectDto : dtoList) {
            Long collectType = platUserCollectDto.getCollectType();
            Long collectTargetId = platUserCollectDto.getCollectTargetId();
            if (collectType == PlatUserCollectEnums.COLLECTTYPE_WELFLARE.getValueLong()) {
                welflareIdList.add(collectTargetId);
            }
            if (collectType == PlatUserCollectEnums.COLLECTTYPE_GAME.getValueLong()) {
                gameIdList.add(collectTargetId);
            }
        }
        if (CollectionUtil.isNotEmpty(welflareIdList)) {
            List<PlatWelfareMessagePojo> platWelfareMessagePojos = platWelfareMessageService.listByIds(welflareIdList);
            if (CollectionUtil.isNotEmpty(platWelfareMessagePojos)) {
                platWelfareMessageMap = platWelfareMessagePojos.stream().collect(Collectors.toMap(PlatWelfareMessagePojo::getId, platWelfareMessagePojo -> platWelfareMessagePojo, (v1, v2) -> v1));
            }
        }
        if (CollectionUtil.isNotEmpty(gameIdList)) {
            List<PlatGameInfoPojo> platGameInfoPojos = gameInfoService.listByIds(gameIdList);
            if (CollectionUtil.isNotEmpty(platGameInfoPojos)) {
                gameMap = platGameInfoPojos.stream().collect(Collectors.toMap(PlatGameInfoPojo::getId, platGameInfoPojo -> platGameInfoPojo, (v1, v2) -> v1));
            }
        }
        for (PlatUserCollectDto platUserCollectDto : dtoList) {
            Long collectType = platUserCollectDto.getCollectType();
            Long collectTargetId = platUserCollectDto.getCollectTargetId();
            Object targetInfo = null;
            if (collectType == PlatUserCollectEnums.COLLECTTYPE_WELFLARE.getValueLong()) {
                targetInfo = platWelfareMessageMap.get(collectTargetId);
            }
            if (collectType == PlatUserCollectEnums.COLLECTTYPE_GAME.getValueLong()) {
                targetInfo = gameMap.get(collectTargetId);
            }
            platUserCollectDto.setCollectTargetData(targetInfo);
        }

    }


    /**
     * 新增用户收藏
     *
     * @param platUserCollectDto 用户收藏
     * @return 结果
     */
    @Override
    @Transactional
    public boolean add(PlatUserCollectDto platUserCollectDto) {

        PlatUserCollectPojo platUserCollectPojo = BeanUtil.copyProperties(platUserCollectDto, PlatUserCollectPojo.class);
        return this.save(platUserCollectPojo);
    }

    /**
     * 修改用户收藏
     *
     * @param platUserCollectDto 用户收藏
     * @return 结果
     */
    @Override
    @Transactional
    public boolean update(PlatUserCollectDto platUserCollectDto) {
        PlatUserCollectPojo platUserCollectPojo = BeanUtil.copyProperties(platUserCollectDto, PlatUserCollectPojo.class);
        return this.updateById(platUserCollectPojo);
    }

    /**
     * 批量删除用户收藏
     *
     * @param ids 需要删除的用户收藏主键
     * @return 结果
     */
    @Override
    @Transactional
    public boolean removeBatch(List<String> ids) {
        List<Long> idsLong = ids.stream().map(Long::parseLong).collect(Collectors.toList());
        return this.removeBatchByIds(idsLong);
    }


    /**
     * 分页查询${subTable.functionName}信息
     *
     * @param platUserCollectDto
     * @return
     */
    @Override
    public AjaxResult queryPage(PlatUserCollectDto platUserCollectDto) {
        Page<PlatUserCollectPojo> page = new Page<>(platUserCollectDto.getPageNum(), platUserCollectDto.getPageSize());
        LambdaQueryWrapper<PlatUserCollectPojo> wrapper = new LambdaQueryWrapper<PlatUserCollectPojo>();
        //此处可做前置判断
        if (wrapper == null) {
            return AjaxResult.success(page);
        }
        wrapper = buildWrapper(wrapper, platUserCollectDto);
        if (wrapper == null) {
            return AjaxResult.success(page);
        }
        Page<PlatUserCollectPojo> pageResult = this.page(page, wrapper);
        Page<PlatUserCollectDto> finalResult = BeanUtil.copyProperties(pageResult, Page.class);
        List<PlatUserCollectPojo> records = pageResult.getRecords();
        if (CollectionUtil.isNotEmpty(records)) {
            List<PlatUserCollectDto> dtos = BeanUtil.copyToList(records, PlatUserCollectDto.class);
            convertList(dtos);
            finalResult.setRecords(dtos);
        }
        return AjaxResult.success(finalResult);
    }

    private LambdaQueryWrapper<PlatUserCollectPojo> buildWrapper(LambdaQueryWrapper<PlatUserCollectPojo> wrapper, PlatUserCollectDto param) {
        log.info("buildPageWrapper param :{}", param);
        if (wrapper == null) {
            return null;
        }
        Long id = param.getId();
        if (id != null) {
            wrapper.eq(PlatUserCollectPojo::getId, id);
        }
        Long userId = param.getUserId();
        if (userId != null) {
            wrapper.eq(PlatUserCollectPojo::getUserId, userId);
        }
        Long collectType = param.getCollectType();
        if (collectType != null) {
            wrapper.eq(PlatUserCollectPojo::getCollectType, collectType);
        }
        Long collectTargetId = param.getCollectTargetId();
        if (collectTargetId != null) {
            wrapper.eq(PlatUserCollectPojo::getCollectTargetId, collectTargetId);
        }
        String createBy = param.getCreateBy();
        if (StrUtil.isNotBlank(createBy)) {
            wrapper.eq(PlatUserCollectPojo::getCreateBy, createBy);
        }
        Date createTime = param.getCreateTime();
        if (createTime != null) {
            wrapper.eq(PlatUserCollectPojo::getCreateTime, createTime);
        }
        String updateBy = param.getUpdateBy();
        if (StrUtil.isNotBlank(updateBy)) {
            wrapper.eq(PlatUserCollectPojo::getUpdateBy, updateBy);
        }
        Date updateTime = param.getUpdateTime();
        if (updateTime != null) {
            wrapper.eq(PlatUserCollectPojo::getUpdateTime, updateTime);
        }
        String remark = param.getRemark();
        if (StrUtil.isNotBlank(remark)) {
            wrapper.eq(PlatUserCollectPojo::getRemark, remark);
        }
        Long delFlag = param.getDelFlag();
        if (delFlag != null) {
            wrapper.eq(PlatUserCollectPojo::getDelFlag, delFlag);
        }
        log.info("buildPageWrapper result :{}", wrapper);
        return wrapper;
    }
}
